<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="9" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="表名称" prop="tableName">
            <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="表描述" prop="tableComment">
            <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
          
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportTable"
              v-hasPermi="['infra:info-table-collect:create']">导入</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <div class="tableDescribe">
          <span>资料表数据</span>
          <el-divider></el-divider>
        </div>

        <!-- 列表 -->
        <el-table v-loading="loading" :data="tableList" ref="multipleTable" @row-click="handleRowClick"
          :row-class-name="tableRowClassName">
          <el-table-column label="表名称" align="center" prop="tableName" min-width="30%" />
          <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" min-width="30%" />
          <el-table-column label="操作" align="center" min-width="30%" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['infra:info-table-collect:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
          @pagination="getList" />


        <!-- 基于 DB 导入 -->
        <import-table ref="import" @ok="handleQuery" />
      </el-col>
      <el-col :span="15" :xs="24">
        <div class="tableDescribe">
          <span>字段数据</span>
          <el-divider></el-divider>
        </div>
        <el-table ref="dragTable" :data="columns" row-key="columnId" :max-height="tableHeight"
          @cell-dblclick="handDbFieldClick">
          <el-table-column label="字段列名" align="center" p prop="columnName" width="200" :show-overflow-tooltip="true" />
          <el-table-column label="字段备注" align="center" prop="columnComment" min-width="10%"
            :show-overflow-tooltip="true" />
          <el-table-column label="物理类型" align="center" prop="dataType" min-width="10%" :show-overflow-tooltip="true" />
          <el-table-column label="Java类型" align="center" prop="javaType" min-width="10%" show-overflow-tooltip />
          <el-table-column label="java属性" align="center" prop="javaField" min-width="10%" show-overflow-tooltip />
        </el-table>
      </el-col>
      <!-- 对话框(添加 / 修改) -->
      <el-dialog :title="title" :visible.sync="openColumn" width="400px" v-dialogDrag append-to-body>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="字段列名" prop="columnName">
            <el-input v-model="form.columnName" placeholder="请输入字段列名" />
          </el-form-item>
          <el-form-item label="字段备注" prop="columnComment">
            <el-input v-model="form.columnComment" placeholder="请输入字段备注" />
          </el-form-item>
          <el-form-item label="物理类型" prop="dataType">
            <el-input v-model="form.dataType" placeholder="请输入物理类型" />
          </el-form-item>
          <el-form-item label="Java类型" prop="javaType">
            <el-select v-model="form.javaType">
              <el-option label="Long" value="Long" />
              <el-option label="String" value="String" />
              <el-option label="Integer" value="Integer" />
              <el-option label="Double" value="Double" />
              <el-option label="BigDecimal" value="BigDecimal" />
              <el-option label="LocalDateTime" value="LocalDateTime" />
              <el-option label="Boolean" value="Boolean" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="插入" prop="createOperation">
            <el-checkbox true-label="true" false-label="false" v-model="form.createOperation"></el-checkbox>
          </el-form-item>
          <el-form-item label="编辑" prop="updateOperation">
            <el-checkbox true-label="true" false-label="false" v-model="form.updateOperation"></el-checkbox>
          </el-form-item>
          <el-form-item label="列表" prop="listOperationResult">
            <el-checkbox true-label="true" false-label="false" v-model="form.listOperationResult"></el-checkbox>
          </el-form-item>
          <el-form-item label="查询" prop="listOperation">
            <el-checkbox true-label="true" false-label="false" v-model="form.listOperation"></el-checkbox>
          </el-form-item> -->
          <!-- <el-form-item label="允许空" prop="nullable">
            <el-checkbox true-label="true" false-label="false" v-model="form.nullable"></el-checkbox>
          </el-form-item> -->
          <!-- <el-form-item label="显示类型" prop="htmlType">
            <el-select v-model="form.htmlType">
              <el-option label="文本框" value="input" />
              <el-option label="文本域" value="textarea" />
              <el-option label="下拉框" value="select" />
              <el-option label="单选框" value="radio" />
              <el-option label="复选框" value="checkbox" />
              <el-option label="日期控件" value="datetime" />
              <el-option label="图片上传" value="imageUpload" />
              <el-option label="文件上传" value="fileUpload" />
              <el-option label="富文本控件" value="editor" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="助记码" prop="mnemonicCode">
          <el-input v-model="form.mnemonicCode" placeholder="请输入助记码" />
        </el-form-item> -->
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import { getCodegenTablePage, deleteCodegen, getCodegenDetail } from "@/api/infra/infoTableCollect";
import importTable from "./importTable";
// 代码高亮插件
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import { getInfoColumnCollect,updateInfoColumnCollect } from "@/api/infra/infoColumnCollect";
import { getDataSourceConfigList } from "@/api/infra/dataSourceConfig";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
hljs.registerLanguage("typescript", require("highlight.js/lib/languages/typescript"));
export default {
  name: "InfraCodegen",
  components: { importTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: "",
      // 选中表数组
      tableNames: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表数据
      tableList: [],
      // 日期范围
      dateRange: "",
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        tableName: undefined,
        tableComment: undefined,
        createTime: []
      },

      // 数据源列表
      dataSourceConfigs: [],
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表详细信息
      table: {},
      // 表单参数
      form: {},
      openColumn: false,
      title: ""
    };
  },
  created() {
    this.getList();
    // 加载数据源
    getDataSourceConfigList().then(response => {
      this.dataSourceConfigs = response.data;
    });

  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time !== this.uniqueId) {
      this.uniqueId = time;
      this.resetQuery();
    }
  },
  methods: {
    /** 查询表集合 */
    getList() {
      this.loading = true;
      getCodegenTablePage(this.queryParams).then(response => {
        this.tableList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
        if (this.tableList.length > 0) {
          this.tableList[0].className = "tableSelectedRowBgColor";

          this.getCloumByTableId(this.tableList[0].id)
        }
      }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 高亮显示 */
    highlightedCode(item) {
      // const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
      // var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      const language = item.filePath.substring(item.filePath.lastIndexOf('.') + 1)
      const result = hljs.highlight(language, item.code || "", true);
      return result.value || '&nbsp;';
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    /** 生成 files 目录 **/
    handleFiles(datas) {
      let exists = {}; // key：file 的 id；value：true
      let files = [];
      // 遍历每个元素
      for (const data of datas) {
        let paths = data.filePath.split('/');
        let fullPath = ''; // 从头开始的路径，用于生成 id
        // 特殊处理 java 文件
        if (paths[paths.length - 1].indexOf('.java') >= 0) {
          let newPaths = [];
          for (let i = 0; i < paths.length; i++) {
            let path = paths[i];
            if (path !== 'java') {
              newPaths.push(path);
              continue;
            }
            newPaths.push(path);
            // 特殊处理中间的 package，进行合并
            let tmp = undefined;
            while (i < paths.length) {
              path = paths[i + 1];
              if (path === 'controller'
                || path === 'convert'
                || path === 'dal'
                || path === 'enums'
                || path === 'service'
                || path === 'vo' // 下面三个，主要是兜底。可能考虑到有人改了包结构
                || path === 'mysql'
                || path === 'dataobject') {
                break;
              }
              tmp = tmp ? tmp + '.' + path : path;
              i++;
            }
            if (tmp) {
              newPaths.push(tmp);
            }
          }
          paths = newPaths;
        }
        // 遍历每个 path， 拼接成树
        for (let i = 0; i < paths.length; i++) {
          // 已经添加到 files 中，则跳过
          let oldFullPath = fullPath;
          // 下面的 replaceAll 的原因，是因为上面包处理了，导致和 tabs 不匹配，所以 replaceAll 下
          fullPath = fullPath.length === 0 ? paths[i] : fullPath.replaceAll('.', '/') + '/' + paths[i];
          if (exists[fullPath]) {
            continue;
          }
          // 添加到 files 中
          exists[fullPath] = true;
          files.push({
            id: fullPath,
            label: paths[i],
            parentId: oldFullPath || '/'  // "/" 为根节点
          });
        }
      }
      return files;
    },
    /** 节点单击事件 **/
    handleNodeClick(data, node) {
      if (node && !node.isLeaf) {
        return false;
      }
      // 判断，如果非子节点，不允许选中
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      const tableId = row.id;
      const tableName = row.tableName || this.tableNames[0];
      const params = { pageNum: this.queryParams.pageNum };
      this.$tab.openPage("修改[" + tableName + "]生成配置", '/codegen/edit/' + tableId, params);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tableIds = row.id;
      this.$modal.confirm('是否确认删除表名称为"' + row.tableName + '"的数据项?').then(function () {
        return deleteCodegen(tableIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 数据源配置的名字
    dataSourceConfigNameFormat(row, column) {
      for (const config of this.dataSourceConfigs) {
        if (row.dataSourceConfigId === config.id) {
          return config.name;
        }
      }
      return '未知【' + row.leaderUserId + '】';
    },
    //点击行触发，切换复选框状态
    handleRowClick(row) {
      this.tableList.forEach((item) => {
        item.className = "normal";
      });
      this.$refs.multipleTable.toggleRowSelection(row);
      if (row.className === "normal") {
        row.className = "tableSelectedRowBgColor";
      } else {
        row.className = "normal";
      }

      this.getCloumByTableId(row.id)
    },
    // 选中背景色
    tableRowClassName({ row }) {
      return row.className;
    },
    getCloumByTableId(tableId) {
      getCodegenDetail(tableId).then(res => {
        this.table = res.data.table;
        this.columns = res.data.columns;
      });
    },
    /* 
 表格单元格双击事件
 row:双击当前行数据
 cloumn:双击当前列
  */
    handDbFieldClick(row, column) {
      this.reset();
      getInfoColumnCollect(row.id).then(response => {
        this.form = response.data
      })
      this.openColumn = true;
      this.title = "修改元素信息";
    },
    submitForm() {

    },
    cancel() {
      this.openColumn = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {

      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
  }
};
</script>
<style>
.tableSelectedRowBgColor td {
  background-color: #fedcbd !important;
}

.tableDescribe {
  color: rgb(0, 0, 128);
  padding: 20px;
  text-align: center;
  font-size: 16px;
  font-weight: 800;
  height: 80px;
  background-color: rgb(248, 248, 249);
}
</style>
